#include <stdlib.h>


#include <QGridLayout>
#include <QtGlobal>
//#include "RF_functions.h"
#include <qtoolbar.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qfiledialog.h>
#include <qstatusbar.h>
#include <qfileinfo.h>
#include <qslider.h>
#include <qtimer.h>
#include <qcombobox.h>
#include <qstring.h>
#include <qcheckbox.h>
#include <qcolordialog.h>
#include <qfontdialog.h>

#include "Plot2D.h"

//#include "colormapreader.h"
//#include "lightingdlg.h"

//
//  Initialize main window
//

using namespace std;

class Zoomer: public QwtPlotZoomer
{
public:
    Zoomer(int xAxis, int yAxis, QwtPlotCanvas *canvas):
            QwtPlotZoomer(xAxis, yAxis, canvas)
    {
        setSelectionFlags(QwtPicker::DragSelection | QwtPicker::CornerToCorner);
        setTrackerMode(QwtPicker::AlwaysOff);
        setRubberBand(QwtPicker::NoRubberBand);

        // RightButton: zoom out by 1
        // Ctrl+RightButton: zoom out to full size


        setMousePattern(QwtEventPattern::MouseSelect2,
                        Qt::RightButton, Qt::ControlModifier);

        setMousePattern(QwtEventPattern::MouseSelect3,
                        Qt::RightButton);
    }
};
Plot_2D::Plot_2D(QWidget *parent):
        QwtPlot(parent)
{

    d_zoomer[0] = new Zoomer( QwtPlot::xBottom, QwtPlot::yLeft,this->canvas());
    d_zoomer[0]->setRubberBand(QwtPicker::RectRubberBand);
    d_zoomer[0]->setRubberBandPen(QColor(Qt::green));
    d_zoomer[0]->setTrackerMode(QwtPicker::ActiveOnly);
    d_zoomer[0]->setTrackerPen(QColor(Qt::red));

    d_zoomer[1] = new Zoomer(QwtPlot::xTop, QwtPlot::yRight,this->canvas());

    d_panner = new QwtPlotPanner(this->canvas());
    d_panner->setMouseButton(Qt::MidButton);

    d_picker = new QwtPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft, QwtPicker::PointSelection | QwtPicker::DragSelection,QwtPlotPicker::CrossRubberBand, QwtPicker::AlwaysOn,this->canvas());
    d_picker->setRubberBandPen(QColor(Qt::green));
    d_picker->setRubberBand(QwtPicker::CrossRubberBand);
    d_picker->setTrackerPen(QColor(Qt::black));
    connect(d_picker, SIGNAL(moved(const QPoint &)), SLOT(moved(const QPoint &)));
    connect(d_picker, SIGNAL(selected(const QwtPolygon &)),SLOT(selected(const QwtPolygon &)));

    this->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(showContextMenuFor_plot2D(const QPoint &)));



}

//
//  Set a plain canvas frame and align the scales to it
//
void Plot_2D::alignScales()
{
    // The code below shows how to align the scales to
    // the canvas frame, but is also a good example demonstrating
    // why the spreaded API needs polishing.

    canvas()->setFrameStyle(QFrame::Box | QFrame::Plain );
    canvas()->setLineWidth(1);

    for ( int i = 0; i < QwtPlot::axisCnt; i++ )
    {
        QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(i);
        if ( scaleWidget )
            scaleWidget->setMargin(0);

        QwtScaleDraw *scaleDraw = (QwtScaleDraw *)axisScaleDraw(i);
        if ( scaleDraw )
            scaleDraw->enableComponent(QwtAbstractScaleDraw::Backbone, false);
    }
}


//  Generate new values 

void Plot_2D::InitPlot(QWidget *parent)
{
    // Disable polygon clipping
    QwtPainter::setDeviceClipping(false);

    QGridLayout *layout = new QGridLayout();

    layout->addWidget(this); // spacer

    parent->setLayout(layout);

    canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
    canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false);

#if QT_VERSION >= 0x040000
#ifdef Q_WS_X11
    /*
       Qt::WA_PaintOnScreen is only supported for X11, but leads
       to substantial bugs with Qt 4.2.x/Windows
     */
    canvas()->setAttribute(Qt::WA_PaintOnScreen, true);
#endif
#endif
    alignScales();

    // Axis
    enableAxis(QwtPlot::yRight);
    setAxisTitle(QwtPlot::xBottom, "Time/seconds");
    setAxisScale(QwtPlot::xBottom, 0, 50);

    setAxisTitle(QwtPlot::yLeft, "Values");
    setAxisScale(QwtPlot::yLeft, -1.5, 20);

    setAxisTitle(QwtPlot::yRight, "Values");
    setAxisScale(QwtPlot::yRight, -1.5, 20);


}
void Plot_2D::setplot(QList<float> x,QList<float> y1, QList<float> y2, QString LegendL, QString LegendR)
{
    QVector<qreal> x_qreal,y1_qreal,y2_qreal;
    QFont serifFont("Times", 10, 75);
    //this->
    QwtPlotCurve *cRight = new QwtPlotCurve(LegendR.toAscii());
    QwtPlotCurve *cLeft = new QwtPlotCurve(LegendL.toAscii());
    QwtSplineCurveFitter *curveFitter;




    /*   xMap[i].setScaleInterval(-5, 1.1);
    yMap[i].setScaleInterval(-1.1, 5.0);
    curve[i].setStyle(QwtPlotCurve::Lines);
    */
    for(int i=0;i<x.count();i++){
        x_qreal.append(x.at(i));
    }
    // Axis

    double min =  x_qreal.first();
    double max =  x_qreal.last();
    setAxisScale(QwtPlot::xBottom,myMin(x_qreal),myMax(x_qreal));

    // Insert new curves
    if(!LegendR.contains("none"))
    {
        enableAxis(QwtPlot::yRight);
        for(int i=0;i<x.count();i++){
            y2_qreal.append(y2.at(i));
        }

        cRight->attach(this);
        cRight->setPen(QPen(Qt::red));
        cRight->setYAxis(QwtPlot::yRight);
        cRight->setData(x_qreal, y2_qreal);
        cRight->setSymbol(QwtSymbol(QwtSymbol::Diamond,QColor(Qt::blue), QColor(Qt::black), QSize(5,5)));

        curveFitter = new QwtSplineCurveFitter();
        curveFitter->setSplineSize(150);
        cRight->setCurveAttribute(QwtPlotCurve::Fitted, true);
        curveFitter->setFitMode(QwtSplineCurveFitter::Spline);
        cRight->setCurveFitter(curveFitter);

        min =  y2_qreal.first();
        max =  y2_qreal.last();
        setAxisScale(QwtPlot::yRight, myMin(y2_qreal),myMax(y2_qreal));
    }
    else{
        enableAxis(QwtPlot::yRight, false);
        cRight->detach();
        cRight->hide();
    }
    if(!LegendL.contains("none"))
    {

        for(int i=0;i<x.count();i++){
            y1_qreal.append(y1.at(i));
        }

        cLeft->attach(this);
        cLeft->setPen(QPen(Qt::blue));
        cLeft->setData(x_qreal, y1_qreal);
        cLeft->setSymbol(QwtSymbol(QwtSymbol::XCross,QColor(Qt::blue), QColor(Qt::black), QSize(5,5)));

        curveFitter = new QwtSplineCurveFitter();
        curveFitter->setSplineSize(150);
        cLeft->setCurveAttribute(QwtPlotCurve::Fitted, true);
        curveFitter->setFitMode(QwtSplineCurveFitter::Spline);
        cLeft->setCurveFitter(curveFitter);

        min =  y1_qreal.first();
        max =  y1_qreal.last();
        setAxisScale(QwtPlot::yLeft,myMin(y1_qreal),myMax(y1_qreal));
    }
    else{
        cLeft->hide();
        cLeft->detach();
    }

    //  Insert zero line at y = 0
    /* QwtPlotMarker *d_mrk1 = new QwtPlotMarker();
    d_mrk1->setValue(0.0, 0.0);
    d_mrk1->setLineStyle(QwtPlotMarker::VLine);
    d_mrk1->setLabelAlignment(Qt::AlignRight | Qt::AlignBottom);
    d_mrk1->setLinePen(QPen(Qt::green, 0, Qt::DashDotLine));
    d_mrk1->attach(this);
    QwtText text("");
    text.setFont(QFont("Helvetica", 10, QFont::Bold));
    text.setColor(Qt::green);
    d_mrk1->setLabel(text);
    d_mrk1->attach(this);
*/
    replot();
}

void Plot_2D::showInfo(QString text)
{
    if ( text == QString::null )
    {
        if ( d_picker->rubberBand() )
            text = "Cursor Pos: Press left mouse button in plot region";
        else
            text = "Zoom: Press mouse button and drag";
    }

#ifndef QT_NO_STATUSBAR
#if QT_VERSION >= 0x040000
    //statusBar()->showMessage(text);
#else
    statusBar()->message(text);
#endif
#endif
}

void Plot_2D::moved(const QPoint &pos)
{
    QString info;
    info.sprintf("Freq=%g, Ampl=%g, Phase=%g",
                 this->invTransform(QwtPlot::xBottom, pos.x()),
                 this->invTransform(QwtPlot::yLeft, pos.y()),
                 this->invTransform(QwtPlot::yRight, pos.y())
                 );
    showInfo(info);
}

void Plot_2D::selected(const QwtPolygon &)
{
    showInfo("");
}

void Plot_2D::Show_Diag_properties()
{
config = new Plot_2D_config;
    list_of_graph = new QList<Graph>;
    config->gridlinetype="Solid Line";
    config->GridColor=Qt::blue;
    config->BackGroundColor=Qt::red;
    config->showgrid = true;

    config->xAxis.Label="X label";
    config->xAxis.autoScale=false;
    config->xAxis.limit_min =1;
    config->xAxis.limit_max =10;
    config->xAxis.step =1;
    config->xAxis.log= true;

    config->ylAxis.Label="Left label";
    config->ylAxis.autoScale=true;
    config->ylAxis.limit_min =2;
    config->ylAxis.limit_max =20;
    config->ylAxis.step =2;
    config->ylAxis.log=false;

    config->yrAxis.Label="Right label";
    config->yrAxis.autoScale=false;
    config->yrAxis.limit_min =3;
    config->yrAxis.limit_max =30;
    config->yrAxis.step =3;
    config->yrAxis.log=true;

    Plot2D_Dialog *plot_2D_properties = new Plot2D_Dialog(config,list_of_graph);
    plot_2D_properties->Load_Default();
    plot_2D_properties->exec();

}

void Plot_2D::setplot_from_diag()
{
    qDebug("setplot_from_dialog");
}


void Plot_2D::showContextMenuFor_plot2D(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    //  contextMenu.setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));

    QAction *action = new QAction(tr("Edit Properties"), this);
    //action->setShortcut(QKeySequence("ctrl+x"));
    contextMenu.addAction(action);
    connect(action, SIGNAL(triggered()),this, SLOT (Show_Diag_properties()));
    contextMenu.exec(mapToGlobal(pos));
}


